import 'package:get/get.dart';
import 'package:xiaomi_shop/app/services/cartService.dart';
import 'package:xiaomi_shop/app/services/storage.dart';
import 'package:xiaomi_shop/app/services/userService.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/index.dart';

class CartController extends GetxController {
  var totalPrice = 0.obs;
  var list = <ShopModel>[].obs;
  RxBool selectAll = false.obs;
  var selectedCount = 0.obs;
  RxBool isEdit = false.obs;

  @override
  void onInit() {
    super.onInit();
    getCartData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 获取购物车商品
  void getCartData() async {
    List<ShopModel> tempData = await CartService.getCartData();
    list.value = tempData;
    calculatePrice();
  }

  // 计算结算价格
  void calculatePrice() {
    var tempPrice = 0;
    List selectedList =
        list.value.where((model) => (model as ShopModel).selected).toList();
    selectedCount.value = selectedList.length;
    for (var element in selectedList) {
      ShopModel model = element as ShopModel;
      tempPrice += (model.price!.toInt() * model.buyNumber);
    }
    totalPrice.value = tempPrice;
    print(totalPrice);
    update();
  }

  // 全选
  void selectAllShop() {
    list.value.forEach((element) {
      ShopModel model = element as ShopModel;
      model.selected = selectAll.value;
    });
    calculatePrice();
  }

  // 删除购物车内商品
  void deleteShop() {
    Get.defaultDialog(
      title: "温馨提示",
      middleText: "确定要将这${selectedCount.value}件商品删除？",
      textCancel: "取消",
      textConfirm: "确定",
      onCancel: () {},
      onConfirm: () {
        list.removeWhere((element) => (element as ShopModel).selected);
        Storage.setData("CART_SHOP_LIST", list);
        Get.back();
        calculatePrice();
      },
    );
  }

  // 结算购物车
  void settlement() async {
    // 判断用户是否登录
    bool loginState = await UserService.getUserLoginState();
    if (loginState) {
      if (selectedCount.value > 0) {
        List selectedList =
            list.value.where((model) => (model as ShopModel).selected).toList();
        Get.toNamed("/checkout", arguments: {"shopList": selectedList});
      } else {
        Toast.show("请选择需要结算的商品");
      }
    } else {
      // 先去登录
      Get.toNamed("/phone-one-click-login");
    }
  }

  // 判断是否选择了全部商品
  void isCheckAll() {
    selectAll.value =
        list.value.every((element) => (element as ShopModel).selected);
  }
}
